import sys
import hashlib

def file_md5(path):
    """计算文件的MD5值"""
    hash_md5 = hashlib.md5()
    with open(path, "rb") as f:
        for chunk in iter(lambda: f.read(4096), b""):
            hash_md5.update(chunk)
    return hash_md5.hexdigest()

def compare_files(file1, file2):
    # 先快速判断是否一致
    md5_1 = file_md5(file1)
    md5_2 = file_md5(file2)

    if md5_1 == md5_2:
        print("✅ 两个文件内容完全一致")
        return

    print("⚠️ 文件内容不一致，逐行对比中...\n")

    with open(file1, "r", encoding="utf-8", errors="ignore") as f1, \
         open(file2, "r", encoding="utf-8", errors="ignore") as f2:

        line_num = 1
        diff_found = False
        while True:
            l1 = f1.readline()
            l2 = f2.readline()
            
            if not l1 and not l2:
                break  # 两个文件都到末尾了

            if l1 != l2:
                diff_found = True
                print(f"第 {line_num} 行不同：")
                print(f"  {file1} -> {l1.strip()}")
                print(f"  {file2} -> {l2.strip()}\n")

            line_num += 1

        if not diff_found:
            print("⚠️ 文件大小相同但内容有差异（可能是换行符/编码差异）")
        else:
            print("❌ 已显示所有不同的行")

if __name__ == "__main__":
    if len(sys.argv) != 3:
        print(f"用法: python {sys.argv[0]} file1 file2")
        sys.exit(1)

    file1, file2 = sys.argv[1], sys.argv[2]
    compare_files(file1, file2)
